<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>商品列表</el-breadcrumb-item>
            <el-breadcrumb-item>添加商品</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片信息区 -->
        <el-card>
          <!-- 提示框 -->
          <el-alert title="添加商品信息" type="info" center show-icon :closable="false">
          </el-alert>

          <!-- 步骤条 -->
          <el-steps :active="arrivalstep - 0" align-center finish-status="success">
            <el-step title="基本信息"></el-step>
            <el-step title="商品参数"></el-step>
            <el-step title="商品属性"></el-step>
            <el-step title="商品图片"></el-step>
            <el-step title="商品内容"></el-step>
            <el-step title="完成"></el-step>
          </el-steps>

          <!-- 左侧Tab栏 -->
          <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" label-position='top'>
          <el-tabs tab-position="left" v-model="arrivalstep" :before-leave="beforeTabLeave" @tab-click="tabClick">
            <el-tab-pane label="基本信息" name='0'>
              <el-form-item label="商品名称" prop="goods_name">
                <el-input v-model="addForm.goods_name"></el-input>
              </el-form-item>
              <el-form-item label="商品价格" prop="goods_price">
                <el-input v-model="addForm.goods_price" type="number"></el-input>
              </el-form-item>
              <el-form-item label="商品重量" prop="goods_weight">
                <el-input v-model="addForm.goods_weight" type="number"></el-input>
              </el-form-item>
              <el-form-item label="商品数量" prop="goods_number">
                <el-input v-model="addForm.goods_number" type="number"></el-input>
              </el-form-item>
              <el-form-item label="商品分类" prop="goods_cat">
                <el-cascader :options="goodsCateList" :props="goodsCate" v-model="addForm.goods_cat" @change="handleChange">
                </el-cascader>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品参数" name='1'>
              <el-form-item v-for="(item,i) in dynamicParameterList" :key="i" :label="item.attr_name">
                <el-checkbox-group v-model="item.attr_vals">
                  <el-checkbox :label="item2" v-for="(item2,i2) in item.attr_vals" :key="i2" border></el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品属性" name='2'>
              <el-form-item :label="item.attr_name" v-for="item in staticPropertiesList" :key="item.attr_id">
                <el-input v-model="item.attr_vals"></el-input>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品图片" name='3'>
              <!-- 上传图片至后台 -->
              <el-upload :action="uploadUrl" :on-preview="handlePreview" :on-remove="handleRemove" :file-list="fileList" list-type="picture" :headers="headerInfo" :on-success="handleSuccess">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
              </el-upload>
            </el-tab-pane>
            <el-tab-pane label="商品内容" name='4'>
              <quill-editor v-model="addForm.goods_introduce"></quill-editor>
              <el-button type="primary" class="add_btn_style" @click="addNewGoodsBtn">添加商品</el-button>
            </el-tab-pane>
          </el-tabs>
          </el-form>
        </el-card>

        <!-- 预览图片 -->
    <el-dialog title="预览图片" :visible.sync="previewDialogVisible" width="50%">
      <img :src="previewUrl" alt="" class="preview_img_style">
    </el-dialog>
    </div>
</template>

<script>
import _ from 'lodash'
export default {
  data() {
    return {
      // 到达第几步
      arrivalstep: '0',
      // 添加商品表单
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      // 添加商品验证规则
      addFormRules: {
        goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        goods_price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        goods_weight: [{ required: true, message: '请输入商品重量', trigger: 'blur' }],
        goods_number: [{ required: true, message: '请输入商品数量', trigger: 'blur' }],
        goods_cat: [{ required: true, message: '请输入商品数量', trigger: 'blur' }]
      },
      // 商品分类级联选择框配置
      goodsCate: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      // 商品分类级联选择框数据列表
      goodsCateList: [],
      // 商品动态参数列表
      dynamicParameterList: [],
      // 商品静态属性列表
      staticPropertiesList: [],
      // 上传图片地址
      uploadUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 上传的文件列表
      fileList: [],
      // 设置上传的请求头
      headerInfo: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 预览图片对话框显示与隐藏
      previewDialogVisible: false,
      // 要预览图片的 URL
      previewUrl: ''
    }
  },
  created() {
    this.getGoodsCate()
  },
  methods: {
    // 获取商品分类
    async getGoodsCate() {
      const { data: res } = await this.$http.get('/categories')
      if (res.meta.status !== 200) {
        return this.$message({
          showClose: true,
          message: '获取商品分类列表失败',
          type: 'error'
        })
      }
      this.goodsCateList = res.data
    },
    // 监听级联选择框改变事件
    handleChange() {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },
    // 监听 Tab 栏切换
    beforeTabLeave(activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message({
          showClose: true,
          message: '请选择商品分类！',
          type: 'error'
        })
        return false
      }
    },
    // 获取商品动态参数
    async getParameter() {
      const { data: res } = await this.$http.get(`categories/${this.cetaId}/attributes`, { params: { sel: this.paramsSel } })
      if (res.meta.status !== 200) {
        return this.$message({
          showClose: true,
          message: '获取动态参数列表失败！',
          type: 'error'
        })
      }
      if (this.paramsSel === 'many') {
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals === '' ? [] : item.attr_vals.split(' ')
        })
        this.dynamicParameterList = res.data
      } else {
        this.staticPropertiesList = res.data
      }
    },
    // Tab 栏选中时触发
    tabClick() {
      if (this.arrivalstep === '1') {
        this.getParameter()
      } else if (this.arrivalstep === '2') {
        this.getParameter()
      }
    },
    // 上传图片后，点击图片列表，展示弹框
    handlePreview(file) {
      this.previewUrl = file.response.data.url
      this.previewDialogVisible = true
    },
    // 点击图片列表中的删除按钮
    handleRemove(file) {
      const removeImg = file.response.data.tmp_path
      const i = this.addForm.pics.findIndex(rImg => rImg === removeImg)
      this.addForm.pics.splice(i, 1)
    },
    // 上传成功后的钩子
    handleSuccess(response) {
      if (response.meta.status !== 200) {
        return this.$message({
          showClose: true,
          message: response.meta.msg,
          type: 'error'
        })
      } else {
        this.$message({
          showClose: true,
          message: '上传成功！',
          type: 'success'
        })
        const picsInfo = { pic: response.data.tmp_path }
        this.addForm.pics.push(picsInfo)
      }
    },
    // 添加新的商品
    addNewGoodsBtn() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return this.$message({
            showClose: true,
            message: '请填写商品相关信息！',
            type: 'error'
          })
        }
        const copyAddFrom = _.cloneDeep(this.addForm)
        copyAddFrom.goods_cat = copyAddFrom.goods_cat.join(',')
        this.dynamicParameterList.forEach(item => {
          const dynamicInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(',')
          }
          this.addForm.attrs.push(dynamicInfo)
        })
        this.staticPropertiesList.forEach(item => {
          const staticInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.addForm.attrs.push(staticInfo)
        })
        copyAddFrom.attrs = this.addForm.attrs

        const { data: res } = await this.$http.post('/goods', copyAddFrom)
        if (res.meta.status !== 201) {
          return this.$message({
            showClose: true,
            message: res.meta.msg,
            type: 'error'
          })
        }
        this.$message({
          showClose: true,
          message: '创建商品成功！',
          type: 'success'
        })
        this.$router.push('/goods')
      })
    }
  },
  computed: {
    // 得到分类Id
    cetaId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return null
    },
    // 来获取分类静态参数还是动态参数
    paramsSel() {
      if (this.arrivalstep === '1') {
        return 'many'
      }
      return 'only'
    }
  }
}
</script>

<style lang="less" scoped>
.el-alert {
  font-size: 16px;
}
.el-checkbox {
  margin: 0 15px 15px 10px;
}
.el-form-item {
    margin-bottom: 15px;
}
.preview_img_style{
  width: 100%;
}
.add_btn_style{
  margin-top: 20px;
}
</style>
